import time

from vidcap import new_Dev

from PIL import Image


class Device:

    def __init__(self, dev_num=0):
        self.dev = new_Dev(int(dev_num), 0)

    def quit(self):
        del self.dev

    # 获取当前摄像头名称
    def get_display_name(self):
        return self.dev.getdisplayname()

    # 获取当前摄像头图像，并转换为PIL的Image对象
    def get_image(self, delay=0):
        if delay != 0:
            # 延迟拍摄，摄像头有对焦时间，解决招聘全黑
            self.dev.getbuffer()
            time.sleep(delay)
        buffer, width, height = self.dev.getbuffer()
        if buffer:
            im = Image.frombytes('RGB', (width, height), buffer, 'raw', 'BGR', 0, -1)
            return im
